// pages/login/base-info/info.js
import uploadImg from '../../../utils/uploadImg.js'
import nationData from '../../../utils/data.js'
const T = getApp().globalData.T
const config = getApp().globalData.config
let token = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    isEdit: false,
    uploadUrl: config.host + 'admin/file/singleFile',
    formData: {
      type: 'image'
    },
    fileList: [],
    step1: true,
    step2: false,
    step1Obj: {},
    input01: '',
    input02: '',
    input03: '',
    input04: '',
    input05: '',
    input06: '',
    resumeImg: '/resource/image/avator_default.png',
    idImgVerso: '/resource/image/create_id_verso.png',
    idImgFront: '/resource/image/create_id_front.png',
    companyList:[],
    creditNo:'',
    isOpen:false,
    step2BtnText:'加入',
    isCreateCompany: false,

    postAvator:'',
    nick:'',
    isOpenUploadImg: false,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.origin == 'edit') {
      this.setData({isEdit: true})
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  onShow: function() {
    token = getApp().globalData.token;
    if (this.data.isOpenUploadImg) return ;
    if (this.data.isEdit) {
      this.getDetail();
    }
  },

  toast(text) {
    T.toast({ id: '#toast', text: text });
  },

  /**
   * 获取管理员资料详情
   */
  getDetail() {
    T.req({
      loadTitle: '加载中...',
      url: config.api + 'user/user_info',
      method: 'GET',
      data: {
        token: token
      },
      success: (res) => {
        this.setData({
          resumeImg: res.headImg,
          input01: res.name,
          input02: res.duty,
          input03: res.email,
          input04: res.idNum,
          idImgVerso: res.idPhotoR,
          idImgFront: res.idPhotoD,
          postAvator: res.forumImg,
          nick: res.forumName
        });
      }
    })
  },


  onUpdateAvator() {
    let that = this;
    this.data.isOpenUploadImg = true;
    uploadImg(that, 'image', 'resumeImgUpload')
      .then((res) => {
        that.setData({
          resumeImg: res,
          isOpenUploadImg: false
        })
      })
  },

  onSelectIdVerso() {
    let that = this;
    this.data.isOpenUploadImg = true;
    uploadImg(that, 'image', 'isLoadIdVImg')
      .then((res) => {
        that.setData({
          idImgVerso: res,
          isOpenUploadImg: false
        })
      })
  },

  onSelectIdFront() {
    let that = this;
    this.data.isOpenUploadImg = true;
    uploadImg(that, 'image', 'isLoadIdFImg')
      .then((res) => {
        that.setData({
          idImgFront: res,
          isOpenUploadImg: false
        })
      })
  },

  onClickIndustry() {
    $wuxSelect('#wux-select-industry').open({
      value: '',
      options: getApp().globalData.industryList,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value: value,
            industry: options[index],
          })
        }
      }
    });
  },

  onClickStaff() {
    $wuxSelect('#wux-select-staff').open({
      value: '',
      options: staffNumber,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value: value,
            staff: options[index],
          })
        }
      }
    });
  },

  onClickStreet() {
    $wuxSelect('#wux-select-row').open({
      value: '',
      options: street,
      onConfirm: (value, index, options) => {
        if (index !== -1) {
          this.setData({
            value: value,
            row: options[index],
          })
        }
      }
    });
  },

  onUploadSuccess(e) {
    this.setData({
      fileList: e.detail.fileList.map((n) => {
        // 如果上传失败显示红框
        if (n.status == 'error') {
          return n
        }
        let _resData = JSON.parse(n.res.data);
        if (_resData.code != 200) {
          return Object.assign(n, {
            status: 'error'
          });
        } else {
          return Object.assign(n, {
            status: 'success'
          });
        }
      })
    })
  },
  onUploadFail(e) {
    console.log(e)
  },
  onRemoveImg(e) {
    this.data.fileList.splice(e.detail.index, 1);
  },

  onInput01(e) {
    this.setData({ input01: e.detail.value })
  },
  onInput02(e) {
    this.setData({ input02: e.detail.value })
  },
  onInput03(e) {
    this.setData({ input03: e.detail.value })
  },
  onInput04(e) {
    this.setData({ input04: e.detail.value })
  },
  onInput05(e) {
    let value = e.detail.value.trim();
    this.setData({ input05:  value, creditNo:''});
    if (!this.data.isSearch) {
      this.data.isSearch = true;
      this.data.searchTime = setTimeout( () => {
        this.getComplayList();
        this.data.isSearch = false;
      }, 1000 * 1)
    }
  },
  onInput06(e) {
    this.setData({ input06: e.detail.value })
  },

  onInputNick(e) {
    this.setData({ nick: e.detail.value })
  },

  onUpdatePostAvator() {
    let that = this;
    this.data.isOpenUploadImg = true;
    uploadImg(that, 'image', 'isLoadPostAvator')
      .then((res) => {
        that.setData({
          postAvator: res,
          isOpenUploadImg: false,
        })
      })
  },

  /**
   * 检查姓名与身份证是否一致
   */
  checkIdentNum() {
    let name = this.data.input01;
    let idNum = this.data.input04;
    return new Promise((resolve, reject) => {
      T.req({
        url: config.host + 'admin/id_auth',
        method: 'POST',
        data: {
          idNo: idNum,
          name: name,
        },
        success: (res) => {
          if (res.respCode == "0004") {
            this.toast('输入的身份证号与管理员姓名不匹配');
          } else {
            resolve();
          }
        }
      })
    })
  },

  getComplayList() {
    if (!this.data.input05.trim()) return ;
    T.req({
      url: config.host + 'web/enterprise_list',
      method: 'GET',
      data: {
        wd: this.data.input05.trim()
      },
      success: (res) => {
        if (res.length == 0) return;
        this.setData({
          companyList: res,
          isOpen: true
        });
      }
    })
  },

  /**
   * 查看系统是否存在该公司
   */
  getSystemCompany(name) {
    T.req({
      url: config.api + 'join_platform',
      method: 'GET',
      data: {
        token: token,
        wd: name
      },
      success: (res) => {
        if (res.join) { // 存在
          this.setData({
            step2BtnText: '加入',
            isCreateCompany: false,
          });
        } else {
          this.setData({
            step2BtnText: '创建',
            isCreateCompany: true,
          });
        }
      }
    })
  },  

  onSelectCompany(e) {
    let value = e.currentTarget.dataset.name; 
    let creditNo = e.currentTarget.dataset.creditno;
    this.setData({
      input05: value,
      isOpen: false,
      creditNo: creditNo
    });
    this.getSystemCompany(value);
  },

  joinCompany() {
    let param = {
      token: token,
      company: this.data.input05,
      taxpayerId: this.data.creditNo
    }
    T.req({
      loadTitle: '请求中...',
      url: config.api + 'user/company_info?' + T.param(param),
      method: 'PUT',
      success: (res) => {
        T.toast({id:'#toast', text:'加入成功', success: () => {
          wx.navigateTo({
            url: '../status/status',
          })
        }})
      }
    })
  },

  nextStep1() {
    let obj = {};
    obj.resumeImg = this.data.resumeImg;
    obj.name = this.data.input01
    obj.duty = this.data.input02;
    obj.email = this.data.input03;
    obj.idNum = this.data.input04;
    obj.idPhotoR = this.data.idImgVerso;
    obj.idPhotoD = this.data.idImgFront;

    let isError = false;
    for (const k in obj) {
      if (!obj[k]) {
        isError = true;
      }
    }

    if (/resource/.test(obj.idPhotoD) || /resource/.test(obj.idPhotoR)) {
      isError = true;
    }
    console.log(obj);
    if (isError) {
      this.toast('还有选项没有填写或者输入,请检查');
      return;
    }

    if (!T.regExp.email.test(obj.email)) {
      this.toast('邮箱格式不正确');
      return;
    }

    this.checkIdentNum().then(() => {
      this.data.step1Obj = obj;
      this.setData({
        step1: true,
        step2: false
      })
    });
  },

  nextStep2() {
    if (!this.data.input05 || !this.data.input06) {
      this.toast('还有项没有填写,请检查!');
      return ;
    }
    if (this.data.creditNo != this.data.input06) {
      this.toast('输入的公司名与统一社会信用代码并不符,请检查');
      return ;
    }
    if (this.data.isCreateCompany) {
      this.onKeepAdminInfo().then((res) => {
        let param = {
          company: this.data.input05,
          creditNo: this.data.input06
        }
        wx.navigateTo({
          url: '../company/company?' + T.param(param),
        })
      });
     } else {
      this.onKeepAdminInfo().then(() => {
        this.joinCompany();
      })
     }
  },

  onEditAdminInfo() {
    this.onKeepAdminInfo().then(res => {
      T.toast({id:'#toast', text:'修改成功', success: () => {
        wx.navigateBack({
          delta:1
        })
      }})
    });
  },

  onPrevStep() {
    this.setData({
      step1: false,
      step2: true
    })
  },

  onKeepAdminInfo() {
    let obj = {};
    obj.resumeImg = this.data.resumeImg;
    obj.name = this.data.input01
    obj.duty = this.data.input02;
    obj.email = this.data.input03;
    obj.idNum = this.data.input04;
    obj.idPhotoR = this.data.idImgVerso;
    obj.idPhotoD = this.data.idImgFront;
    if (this.data.isEdit) {
      obj.forumImg = this.data.postAvator;
      obj.forumName = this.data.nick;
    }
    let isError = false;
    for (const k in obj) {
      if (!obj[k]) {
        isError = true;
      }
    }

    if (/resource/.test(obj.idPhotoD) || /resource/.test(obj.idPhotoR)) {
      isError = true;
    }

    if (this.data.isEdit) {
      if (!obj.forumImg) {
        isError = true;
      }
    }
    console.log(obj);
    if (isError) {
      this.toast('还有选项没有填写或者输入,请检查');
      return;
    }

    if (!T.regExp.email.test(obj.email)) {
      this.toast('邮箱格式不正确');
      return;
    }

    return new Promise((resolve,reject) => {
      T.req({
        loadTitle: '请求中...',
        url: config.api + 'user/user_info?token=' + token,
        method: 'PUT',
        data: {
          headImg: obj.resumeImg,
          name: obj.name,
          email:obj.email,
          duty: obj.duty,
          idNum: obj.idNum,
          idPhotoD: obj.idPhotoD,
          idPhotoR: obj.idPhotoR,
          forumName: obj.forumName || '',
          forumImg: obj.forumImg || '',
        },
        success: (res) => {
          resolve(res)
        }
      })
    })
  }
})
